import { defineStore } from "pinia";
import { store } from "@/store";
import {
  addSecurity,
  AddSecurityInfo,
  getSecurity,
  deleteSecurity,
  getPatrol,
  PatrolInfo
} from "@/api/security";
import { useUserStoreHook } from "@/store/modules/user";
import { message } from "@/utils/message";

export type securityType = {
  workId: number;
  workName: string;
  workIdentity: number;
  workPartId: number;
  workStatus: number;
  workPhone: string;
};

export type stateType = {
  total: number;
  patrolTotal: number;
  securityManList: Array<securityType>;
  patrolList: Array<PatrolInfo>;
};

export const useSecurityStore = defineStore({
  id: "pure-security",
  state: (): stateType => ({
    total: 0,
    patrolTotal: 0,
    securityManList: [],
    patrolList: []
  }),
  actions: {
    async getSecurityInfo(currentPage: number, pigeSize: number) {
      await getSecurity({
        id: useUserStoreHook().manageId,
        currentPage,
        pigeSize
      }).then(data => {
        this.total = data.total;
        this.securityManList = data.list;
      });
    },
    async getPatrolInfo(currentPage: number, pigeSize: number) {
      await getPatrol({
        id: useUserStoreHook().manageId,
        currentPage,
        pigeSize
      }).then(data => {
        this.patrolTotal = data.total;
        this.patrolList = data.list;
      });
    },
    addSecurityMan(data: AddSecurityInfo) {
      addSecurity(data).then(() => {
        message("添加成功", { type: "success" });
        useSecurityStoreHook().securityManList.push(data);
      });
    },
    async deleteSecurityMan(data: Array<number>) {
      await deleteSecurity(data).then(() => {
        message("删除成功", { type: "success" });
        const set = new Set();
        for (let i = 0; i < data.length; i++) set.add(data[i]);
        useSecurityStoreHook().securityManList =
          useSecurityStoreHook().securityManList.filter(
            x => !set.has(x.workId)
          );
      });
    }
  }
});

export function useSecurityStoreHook() {
  return useSecurityStore(store);
}
